const { NodeSSH } = require('node-ssh')
import logger from './logger.js'
import config from './config/config'
const ssh = new NodeSSH()

/**
 * 连接到远程主机
 * @param {string} configName 配置名称
 */
async function connect(configName = 'server1') {
  try {
    if (!config.server || !config.server[configName]) {
      throw new Error('ssh.js', `connect-ERROR: \n${configName} not found`)
    }
    const serverConfig = config.server[configName]
    await ssh.connect(serverConfig)
    logger.info('ssh.js', `connect-SUCCESS: \n${configName} connected to ${serverConfig.host}`)
  } catch (err) {
    logger.error('ssh.js', `connect-ERROR: ${configName} failed to connect: ${err.message}`)
    throw new Error(`${configName} failed to connect: ${err.message}`)
  }
}

/**
 * 执行远程命令
 * @param {string} configName 配置名称
 * @param {string} command 要执行的命令
 * @param {object} options 执行选项
 * @returns {Promise<string>} 命令执行结果
 */
export async function execCommand(configName, command, options = {}) {
  await connect(configName)
  try {
    const result = await ssh.execCommand(command, options)
    logger.info('ssh.js', `executeCommand-COMMAND: \n${command}`)
    logger.info('ssh.js', `executeCommand-SUCCESS: \n${result.stdout}`)
    return result.stdout
  } catch (err) {
    logger.error('ssh.js', `executeCommand-COMMAND: \n${command}`)
    logger.error('ssh.js', `executeCommand-ERROR: \n${err.message}`)
    throw err
  } finally {
    ssh.dispose()
  }
}

/**
 * 上传文件到远程主机
 * @param {string} configName 配置名称
 * @param {string} localPath 本地文件路径
 * @param {string} remotePath 远程文件路径
 */
export async function uploadFile(configName, localPath, remotePath) {
  await connect(configName)
  try {
    const status = await ssh.putFile(localPath, remotePath)
    logger.info('ssh.js', `uploadFile-PATH: \n${localPath} -> ${remotePath}`)
    logger.info('ssh.js', `uploadFile-SUCCESS: \n${status}`)
    return status
  } catch (err) {
    logger.error('ssh.js', `uploadFile-PATH: \n${localPath} -> ${remotePath}`)
    logger.error('ssh.js', `uploadFile-ERROR: \n${err.message}`)
    throw err
  } finally {
    ssh.dispose()
  }
}
/**
 * 从远程主机下载文件
 * @param {string} configName 配置名称
 * @param {string} remotePath 远程文件路径
 * @param {string} localPath 本地文件路径
 */
export async function downloadFile(configName, remotePath, localPath) {
  try {
    await connect(configName)
    const status = await ssh.getFile(localPath, remotePath)
    logger.info('ssh.js', `downloadFile-PATH: \n${remotePath} -> ${localPath}`)
    logger.info('ssh.js', `downloadFile-SUCCESS: \n${status}`)
    return status
  } catch (err) {
    logger.error('ssh.js', `downloadFile-PATH: \n${remotePath} -> ${localPath}`)
    logger.error('ssh.js', `downloadFile-ERROR: \n${err.message}`)
    throw err
  } finally {
    ssh.dispose()
  }
}
